package com.moneywelcome.baidu;


import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.json.JSONObject;
import com.moneywelcome.aliyun.AliyunOssUtil;
import com.moneywelcome.exceptions.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 身份证识别
 * 图片状态 image_status
 *         normal-识别正常
 *         reversed_side-身份证正反面颠倒
 *         non_idcard-上传的图片中不包含身份证
 *         blurred-身份证模糊
 *         other_type_card-其他类型证照
 *         over_exposure-身份证关键字段反光或过曝
 *         over_dark-身份证欠曝（亮度过低）
 *         unknown-未知状态
 *
 * 身份证风险类型risk_type:
 *      normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknown-其他未知情况
 */
@Slf4j
@Component
public class IDcard {
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public String getIdcard(String imgUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            //本地文件方式
//            byte[] imgData = FileUtil.readFileByBytes(filePath);
//            String imgStr = Base64Util.encode(imgData);
//            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
//            String param = "id_card_side=" + "front" + "&url=" + imgParam;

            //url方式
            String urlParam=URLEncoder.encode(imgUrl,"UTF-8");
            String param = "id_card_side=" + "front" +"&detect_photo=true"+ "&detect_risk=true"+"&url=" + urlParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken, param);
//            System.out.println(result);
//            log.info("识别身份证信息:{}",result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 身份证肖像面识别
     * @return
     */
    public HashMap<String, String> portraitSideInfo(String imgUrl) {
        HashMap<String, String> idCardMap = new HashMap<>();
        String idcard = this.getIdcard(imgUrl);
        JSONObject jsonObject = new JSONObject(idcard);
        //头像photo
        idCardMap.put("photo",jsonObject.getStr("photo"));
        jsonObject.set("photo","已缓存");
        log.info("身份证人像面识别结果：{}",jsonObject);
        //出生;
        idCardMap.put("出生",parse(idcard,"出生"));
        //性别
        idCardMap.put("性别",parse(idcard,"性别"));
        //姓名
        idCardMap.put("姓名",parse(idcard,"姓名"));
        //民族
        idCardMap.put("民族",parse(idcard,"民族"));
        //住址
        idCardMap.put("住址",parse(idcard,"住址"));
        //公民身份号码
        String idCardNumber = parse(idcard, "公民身份号码");
        idCardMap.put("公民身份号码",parse(idcard,"公民身份号码"));
        //身份证风险类型risk_type:normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknown-其他未知情况
        idCardMap.put("risk_type",jsonObject.getStr("risk_type"));
        //图片状态
        idCardMap.put("image_status",jsonObject.getStr("image_status"));
        //校验
        validate(idCardMap);
        //头像上传到阿里云
        ByteArrayInputStream cardImage = new ByteArrayInputStream(Base64Decoder.decode(idCardMap.get("photo")));
        String fileName="idcard_"+idCardMap.get("公民身份号码")+".jpg";
        aliyunOssUtil.upload(fileName,"vitastar",cardImage);
        //阿里云头像地址
        idCardMap.put("photo","https://vitastar.oss-cn-chengdu.aliyuncs.com/"+fileName);
        return idCardMap;
    }

    /**
     * 身份证国徽面识别
     * @param imgUrl
     * @return
     */
    public HashMap<String, String> emblemSideInfo(String imgUrl) {
        HashMap<String, String> idCardMap = new HashMap<>();
        String idcard = this.getIdcard(imgUrl);
        log.info("身份证国徽面识别结果：{}",idcard);
        //失效日期
        idCardMap.put("失效日期",parse(idcard,"失效日期"));
        //签发机关
        idCardMap.put("签发机关",parse(idcard,"签发机关"));
        //签发日期
        idCardMap.put("签发日期",parse(idcard,"签发日期"));
        //身份证风险类型risk_type
        idCardMap.put("risk_type",new JSONObject(idcard).getStr("risk_type"));
        //校验
        validate(idCardMap);
        //图片状态
        idCardMap.put("image_status",new JSONObject(idcard).getStr("image_status"));
        return idCardMap;
    }


    private void validate(Map idCardMap){
        if(idCardMap.containsValue("")||idCardMap.containsValue(null))
            throw new BaseException("IDCard_AUTH_FAILED","身份证识别失败");
    }

    private String parse(String idcard,String key){
        String words_result = new JSONObject(idcard).getStr("words_result");
        JSONObject priCard = new JSONObject(words_result);
        return new JSONObject(priCard.getStr(key)).getStr("words");
    }


}
